package com.luo.auth.filter;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.luo.auth.annotation.NoAuthorization;
import com.luo.auth.constant.Constants;
import com.luo.auth.exception.ExceptionCodeEnum;
import com.luo.auth.pojo.TokenObj;
import com.luo.auth.service.TokenService;
import com.luo.partner.result.ResultUtil;

@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

	private Logger logger = LoggerFactory.getLogger(AuthorizationInterceptor.class);

	@Autowired
	private TokenService tokenService;

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		try {
			response.setHeader("Access-Control-Allow-Origin", "*");
			// 如果不是映射到方法直接通过
			if (!(handler instanceof HandlerMethod)) {
				return true;
			}
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();
			if (method.getAnnotation(NoAuthorization.class) != null) {
				return true;
			}

			// 从header中得到token
			String authorization = request.getHeader(Constants.AUTHORIZATION);
			if (authorization == null || authorization.trim().equals("")) {
				authorization = request.getParameter(Constants.AUTHORIZATION);
			}
			int i = 0;
			if (null != authorization && !"".equals(authorization.trim())) {
				TokenObj model = tokenService.getToken(authorization);
				if (model != null) {
					i = tokenService.checkToken(model);
				}
				if (i == 1) {
					// 如果token验证成功，将token对应的用户id存在request中，便于之后注入
					request.setAttribute(Constants.CURRENT_USER_ID, model);
					return true;
				}
			}else {
				i = 3;
			}
			response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
			response.setStatus(HttpServletResponse.SC_OK);
			if (i == 0) {
				response.getWriter()
						.write(JSONObject.toJSONString(ResultUtil.error(ExceptionCodeEnum.ERROR00000004.getCode(),
								ExceptionCodeEnum.ERROR00000004.getDesc())));
			} else if (i == 2) {
				response.getWriter()
				.write(JSONObject.toJSONString(ResultUtil.error(ExceptionCodeEnum.ERROR00000003.getCode(),
						ExceptionCodeEnum.ERROR00000003.getDesc())));
			} else if (i == 3) {
				response.getWriter()
				.write(JSONObject.toJSONString(ResultUtil.error(ExceptionCodeEnum.ERROR00000005.getCode(),
						ExceptionCodeEnum.ERROR00000005.getDesc())));
			}
			return false;
		} catch (Exception ex) {
			logger.error(ex.getMessage());
			response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
			response.setStatus(HttpServletResponse.SC_OK);
			response.getWriter().write(JSONObject.toJSONString(ResultUtil.error(ExceptionCodeEnum.ERROR00000001.getCode(),
					ExceptionCodeEnum.ERROR00000001.getDesc())));
			return false;
		}
	}
}
